/**
 * @description 词云
 * 
 */


import echarts from "../echart"
import { useEffect, useRef } from 'react';
import useChartResize from "@/hooks/useChartResize";
import { getWordCloudMock } from "../mockData";

function WordCloud({ configData, chart }) {

  const chartRef = useRef(null)
  const boxRef = useRef(null)


  useEffect(() => {

    // 图表配置项
    let themeConfig = chart.wordCloud


    // 基于准备好的dom，初始化echarts实例
    if (!chartRef.current) {
      let myChart = echarts.init(boxRef.current)
      chartRef.current = myChart
    }


    // 拷贝option
    let wordCloud = JSON.parse(JSON.stringify(themeConfig.option))

    // 数据
    let chartData = getWordCloudMock()
    wordCloud.series[0].data = chartData

    // 颜色 随机
    wordCloud.series[0].textStyle.color = function () {
      return "rgb(" + [Math.round(160 * Math.random()), Math.round(160 * Math.random()), Math.round(160 * Math.random())].join(',') + ')'
    }


    // 词云的maskImage形状
    let maskImageUrl = wordCloud.maskImageUrl

    if (maskImageUrl) {
      var maskImage = new Image();
      maskImage.crossOrigin = 'Anonymous';

      // http://codegen.caihongy.cn/ 不知道为啥不支持跨域，尝试改为https
      maskImage.src = maskImageUrl.replace(/^http:/, 'https:')

      maskImage.onload = () => {
        wordCloud.series[0].maskImage = maskImage
        chartRef.current.setOption(wordCloud, true)
      }
      maskImage.onerror = () => {
        chartRef.current.setOption(wordCloud, true)
      }
    } else {
      chartRef.current.setOption(wordCloud, true)
    }

  }, [chart])


  useChartResize(boxRef, chartRef)
  return (
    <div className='chart-box' ref={boxRef} ></div>
  )
}
export default WordCloud